Exception Handling in Selenium with Python
Exception Handling is an important concept in Selenium Python automation because automated tests interact with dynamic web applications, browsers, WebDriver sessions, frames, alerts, windows, and changing DOM elements. During execution, unexpected conditions can cause Selenium to raise exceptions.
Exception handling allows automation engineers to detect these failures, handle them appropriately, collect useful diagnostic information, perform cleanup operations, and prevent one unexpected error from making the entire automation framework difficult to debug.
Selenium Python provides WebDriver-specific exceptions such as NoSuchElementException, TimeoutException, StaleElementReferenceException, ElementClickInterceptedException, NoSuchFrameException, NoSuchWindowException, and many others. WebDriverException is the base class for WebDriver-related exceptions.
Course Resource: Selenium Training | Register for Course Demo
1. What is Exception Handling?
Exception Handling is a programming technique used to detect and manage runtime errors without allowing the application or automation script to terminate unexpectedly.
In Python, exception handling is mainly performed using the following keywords:
- try - Contains code that may generate an exception.
- except - Handles a specific exception.
- else - Executes when no exception occurs.
- finally - Executes whether an exception occurs or not.
- raise - Manually raises or propagates an exception.
2. Basic Exception Handling Flow
Start
|
v
Execute Code
|
v
Exception Occurs?
/ \
No Yes
| |
v v
Continue Find Matching
except Block
|
v
Handle Exception
|
v
finally
|
v
End
3. Why Exception Handling is Important in Selenium
Selenium tests interact with external systems whose state can change during execution. An element may not exist yet, a locator may become invalid, a page may refresh, a frame may not be available, a browser window may close, or a timeout may occur.
Proper exception handling helps automation frameworks:
- Prevent uncontrolled test termination.
- Identify the actual cause of failures.
- Generate meaningful error messages.
- Capture screenshots when appropriate.
- Perform browser cleanup.
- Improve debugging.
- Support test reporting.
- Separate recoverable failures from genuine test failures.
- Make automation frameworks more maintainable.
4. Basic Python try-except
try:
print(10 / 0)
except:
print("An exception occurred")
Although a bare except: is possible, it is generally better to catch specific exceptions so that the automation framework can respond appropriately.
5. Handling a Specific Exception
try:
number = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
Specific exception handling makes the code easier to understand and prevents unrelated exceptions from being hidden.
6. Selenium Exception Hierarchy
Exception
|
v
WebDriverException
|
+-- NoSuchElementException
+-- TimeoutException
+-- StaleElementReferenceException
+-- ElementNotInteractableException
+-- ElementClickInterceptedException
+-- InvalidElementStateException
+-- NoSuchFrameException
+-- NoSuchWindowException
+-- NoAlertPresentException
+-- UnexpectedAlertPresentException
+-- InvalidSelectorException
+-- JavascriptException
+-- SessionNotCreatedException
+-- NoSuchDriverException
+-- NoSuchCookieException
+-- ScreenshotException
Selenium provides specialized exception classes so automation engineers can identify different types of WebDriver failures and handle them appropriately.
7. Importing Selenium Exceptions
from selenium.common.exceptions import (
NoSuchElementException,
TimeoutException,
StaleElementReferenceException,
ElementNotInteractableException,
ElementClickInterceptedException,
InvalidElementStateException,
NoSuchFrameException,
NoSuchWindowException,
NoAlertPresentException,
UnexpectedAlertPresentException,
InvalidSelectorException,
JavascriptException,
WebDriverException
)
8. NoSuchElementException
NoSuchElementException occurs when Selenium cannot find the requested element at the time the lookup is performed.
Example
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.by import By
try:
username = driver.find_element(By.ID, "username")
username.send_keys("admin")
except NoSuchElementException:
print("Username field was not found")
Possible Causes
- Incorrect locator.
- Element has not appeared yet.
- Page is not loaded as expected.
- Wrong page or URL.
- Element is inside an iframe.
- DOM structure has changed.
- Previous action did not complete successfully.
Better Approach with Explicit Wait
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
username = WebDriverWait(driver, 10).until(
EC.visibility_of_element_located(
(By.ID, "username")
)
)
Instead of immediately searching for a dynamic element, use an appropriate wait condition when the application requires synchronization.
9. TimeoutException
TimeoutException occurs when an operation or wait does not complete within the required amount of time. It is commonly encountered when an explicit wait condition is not satisfied before the timeout expires.
from selenium.common.exceptions import TimeoutException
try:
button = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable(
(By.ID, "login")
)
)
button.click()
except TimeoutException:
print("Login button did not become clickable")
Common Causes
- Element never appeared.
- Incorrect locator.
- Application response was slower than expected.
- Element remained disabled.
- Loading overlay remained visible.
- Expected URL did not occur.
- Expected text did not appear.
10. StaleElementReferenceException
StaleElementReferenceException occurs when Selenium has a reference to an element that is no longer attached to the current DOM. This can happen after page refreshes, DOM replacements, navigation, or JavaScript frameworks rebuilding elements.
Example
from selenium.common.exceptions import StaleElementReferenceException
try:
button = driver.find_element(By.ID, "submit")
# Application updates the DOM
button.click()
except StaleElementReferenceException:
print("The element became stale")
Common Solution
Locate the element again after the DOM has changed.
try:
button = driver.find_element(By.ID, "submit")
button.click()
except StaleElementReferenceException:
button = driver.find_element(By.ID, "submit")
button.click()
Better Approach with Wait
button = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable(
(By.ID, "submit")
)
)
button.click()
11. ElementNotInteractableException
ElementNotInteractableException can occur when Selenium finds an element but the element cannot currently be interacted with. The element may be hidden, disabled, or otherwise not in a state suitable for the requested interaction.
from selenium.common.exceptions import ElementNotInteractableException
try:
driver.find_element(
By.ID, "username"
).send_keys("admin")
except ElementNotInteractableException:
print("Username field is not currently interactable")
Possible Solutions
- Wait for visibility.
- Wait for clickability where appropriate.
- Check whether the element is enabled.
- Verify that the correct element was located.
- Check whether another UI element is blocking the interaction.
12. ElementClickInterceptedException
ElementClickInterceptedException occurs when a click cannot reach the intended element because another element is obscuring or intercepting the click.
from selenium.common.exceptions import ElementClickInterceptedException
try:
driver.find_element(By.ID, "submit").click()
except ElementClickInterceptedException:
print("Another element intercepted the click")
Common Causes
- Popup overlay.
- Cookie banner.
- Loading spinner.
- Modal dialog.
- Animation.
- Another element positioned above the button.
Better Solution
wait = WebDriverWait(driver, 10)
wait.until(
EC.invisibility_of_element_located(
(By.ID, "loader")
)
)
button = wait.until(
EC.element_to_be_clickable(
(By.ID, "submit")
)
)
button.click()
13. InvalidElementStateException
InvalidElementStateException can occur when an operation cannot be completed because the element is in an invalid state for that operation.
from selenium.common.exceptions import InvalidElementStateException
try:
field = driver.find_element(By.ID, "username")
field.clear()
except InvalidElementStateException:
print("Element is not in a valid state for this operation")
14. NoSuchFrameException
NoSuchFrameException occurs when Selenium attempts to switch to a frame that does not exist or cannot be found in the current context.
from selenium.common.exceptions import NoSuchFrameException
try:
driver.switch_to.frame("payment-frame")
except NoSuchFrameException:
print("Payment frame was not found")
Better Approach
try:
WebDriverWait(driver, 10).until(
EC.frame_to_be_available_and_switch_to_it(
(By.ID, "payment-frame")
)
)
except TimeoutException:
print("Payment frame did not become available")
15. NoSuchWindowException
NoSuchWindowException occurs when Selenium attempts to switch to a browser window or tab that does not exist in the current session.
from selenium.common.exceptions import NoSuchWindowException
try:
driver.switch_to.window(window_handle)
except NoSuchWindowException:
print("Browser window does not exist")
Checking Window Handles
print(driver.window_handles)
for handle in driver.window_handles:
print(handle)
16. NoAlertPresentException
NoAlertPresentException occurs when Selenium attempts to interact with an alert when no alert is currently present.
from selenium.common.exceptions import NoAlertPresentException
try:
alert = driver.switch_to.alert
alert.accept()
except NoAlertPresentException:
print("No alert is currently present")
Better Approach with Wait
alert = WebDriverWait(driver, 10).until(
EC.alert_is_present()
)
alert.accept()
17. UnexpectedAlertPresentException
UnexpectedAlertPresentException can occur when an unexpected modal alert blocks WebDriver from executing a command.
from selenium.common.exceptions import UnexpectedAlertPresentException
try:
driver.find_element(By.ID, "submit").click()
except UnexpectedAlertPresentException:
print("An unexpected alert is blocking the browser")
18. InvalidSelectorException
InvalidSelectorException occurs when the selector supplied to Selenium is invalid. This commonly happens with syntactically invalid XPath or CSS selectors.
from selenium.common.exceptions import InvalidSelectorException
try:
driver.find_element(
By.XPATH,
"//*[@id='username'"
)
except InvalidSelectorException:
print("Invalid XPath selector")
Best Practices
- Validate XPath syntax.
- Validate CSS selector syntax.
- Use the correct
By strategy.
- Test locators in browser developer tools.
- Prefer stable locators.
19. JavascriptException
JavascriptException is raised when an error occurs while executing JavaScript supplied by the user.
from selenium.common.exceptions import JavascriptException
try:
driver.execute_script(
"invalid javascript code"
)
except JavascriptException:
print("JavaScript execution failed")
20. NoSuchCookieException
NoSuchCookieException can occur when Selenium cannot find a requested cookie.
from selenium.common.exceptions import NoSuchCookieException
try:
cookie = driver.get_cookie("session_id")
if cookie is None:
print("Cookie was not found")
except NoSuchCookieException:
print("Cookie does not exist")
21. SessionNotCreatedException
SessionNotCreatedException can occur when Selenium cannot create a new browser session.
from selenium.common.exceptions import SessionNotCreatedException
from selenium import webdriver
try:
driver = webdriver.Chrome()
except SessionNotCreatedException:
print("Unable to create browser session")
Possible Causes
- Browser and driver incompatibility.
- Invalid browser configuration.
- Driver startup failure.
- Incorrect browser options.
- Environment or installation problems.
22. NoSuchDriverException
NoSuchDriverException is raised when the required WebDriver cannot be located or specified correctly.
from selenium.common.exceptions import NoSuchDriverException
from selenium import webdriver
try:
driver = webdriver.Chrome()
except NoSuchDriverException:
print("Chrome WebDriver could not be located")
23. WebDriverException
WebDriverException is the base class for Selenium WebDriver exceptions. It can be caught when a framework needs to handle a broad category of WebDriver errors.
from selenium.common.exceptions import WebDriverException
try:
driver.get("https://example.com")
except WebDriverException as e:
print("WebDriver error occurred:", e)
However, catching the broad base exception everywhere can hide the actual cause. Specific exceptions are generally preferable when the framework can respond differently to different failures.
24. Multiple except Blocks
Python allows multiple exception handlers for different types of errors.
try:
element = driver.find_element(By.ID, "login")
element.click()
except NoSuchElementException:
print("Login element was not found")
except ElementClickInterceptedException:
print("Another element blocked the click")
except ElementNotInteractableException:
print("Login element cannot be interacted with")
except Exception as e:
print("Unexpected error:", e)
25. Order of except Blocks
More specific exceptions should normally be handled before broader exception classes.
try:
element = driver.find_element(By.ID, "login")
except NoSuchElementException:
print("Element not found")
except WebDriverException:
print("General WebDriver error")
This structure allows the framework to provide specific handling before falling back to broader WebDriver error handling.
26. Using else with Selenium
The else block executes when no exception occurs in the try block.
try:
element = driver.find_element(By.ID, "username")
except NoSuchElementException:
print("Username field not found")
else:
element.send_keys("admin")
print("Username entered successfully")
27. Using finally with Selenium
The finally block executes whether an exception occurs or not. It is particularly useful for browser cleanup.
driver = None
try:
driver = webdriver.Chrome()
driver.get("https://example.com")
element = driver.find_element(By.ID, "username")
element.send_keys("admin")
except WebDriverException as e:
print("Selenium error:", e)
finally:
if driver:
driver.quit()
28. Complete try-except-else-finally Example
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.common.exceptions import (
NoSuchElementException,
WebDriverException
)
driver = None
try:
driver = webdriver.Chrome()
driver.get("https://example.com")
username = driver.find_element(By.ID, "username")
username.send_keys("admin")
except NoSuchElementException:
print("Username field was not found")
except WebDriverException as e:
print("WebDriver error:", e)
else:
print("Test step completed successfully")
finally:
if driver:
driver.quit()
print("Browser closed")
29. Raising an Exception
The raise keyword can be used when the test framework detects an invalid state and wants to stop or propagate the failure explicitly.
if not login_successful:
raise Exception("Login failed")
30. Raising a Custom Exception
class LoginFailedException(Exception):
pass
if not login_successful:
raise LoginFailedException(
"Login operation failed"
)
31. Custom Exceptions in Selenium Frameworks
Custom exceptions can make a large automation framework easier to understand.
class PageLoadException(Exception):
pass
class LoginException(Exception):
pass
class ElementActionException(Exception):
pass
Example:
try:
WebDriverWait(driver, 15).until(
EC.url_contains("/dashboard")
)
except TimeoutException:
raise LoginException(
"Dashboard was not reached after login"
)
32. Exception Handling with Explicit Waits
Wait-related exceptions are common in Selenium automation. A framework can catch TimeoutException and collect diagnostic information.
try:
login_button = WebDriverWait(
driver, 10
).until(
EC.element_to_be_clickable(
(By.ID, "login")
)
)
login_button.click()
except TimeoutException:
print("Login button was not ready")
driver.save_screenshot("login_timeout.png")
33. Exception Handling with Screenshot
Taking a screenshot at the point of failure can help diagnose UI automation problems.
try:
driver.find_element(
By.ID, "submit"
).click()
except WebDriverException as e:
driver.save_screenshot(
"selenium_error.png"
)
print("Error:", e)
34. Screenshot Utility
def capture_screenshot(driver, filename):
try:
driver.save_screenshot(filename)
print("Screenshot saved:", filename)
except Exception as e:
print("Screenshot failed:", e)
35. Logging Exceptions
Logging is preferable to relying only on print statements in larger automation frameworks.
import logging
logging.basicConfig(
level=logging.INFO
)
try:
driver.find_element(
By.ID, "username"
).send_keys("admin")
except NoSuchElementException as e:
logging.error(
"Username element not found: %s",
e
)
36. Logging Different Exceptions
try:
button = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable(
(By.ID, "submit")
)
)
button.click()
except TimeoutException:
logging.error(
"Submit button was not clickable"
)
except ElementClickInterceptedException:
logging.error(
"Submit click was intercepted"
)
except WebDriverException as e:
logging.error(
"WebDriver failure: %s",
e
)
37. Exception Handling in Page Object Model
Exception handling can be placed inside Page Object methods when the page object can provide meaningful recovery or diagnostic information.
class LoginPage:
USERNAME = (By.ID, "username")
PASSWORD = (By.ID, "password")
LOGIN = (By.ID, "login")
def __init__(self, driver):
self.driver = driver
self.wait = WebDriverWait(driver, 10)
def login(self, username, password):
try:
self.wait.until(
EC.visibility_of_element_located(
self.USERNAME
)
).send_keys(username)
self.wait.until(
EC.visibility_of_element_located(
self.PASSWORD
)
).send_keys(password)
self.wait.until(
EC.element_to_be_clickable(
self.LOGIN
)
).click()
except TimeoutException as e:
self.driver.save_screenshot(
"login_timeout.png"
)
raise e
38. Exception Handling in Test Cases
def test_login(driver):
try:
login_page = LoginPage(driver)
login_page.login(
"admin",
"admin123"
)
assert "/dashboard" in driver.current_url
except AssertionError:
driver.save_screenshot(
"login_assertion_failure.png"
)
raise
except WebDriverException:
driver.save_screenshot(
"webdriver_failure.png"
)
raise
39. Exception Handling vs Waits
Exception handling and waits solve different problems.
| Concept | Purpose |
| Wait | Synchronizes automation with application state. |
| try-except | Handles an exception after an operation fails. |
| Expected Condition | Defines the state Selenium should wait for. |
| finally | Performs cleanup regardless of success or failure. |
| Logging | Records diagnostic information. |
| Screenshot | Captures visual evidence of failure. |
| raise | Explicitly propagates or creates an exception. |
40. Do Not Use Exception Handling as a Replacement for Waits
A common mistake is repeatedly catching NoSuchElementException instead of synchronizing with the application.
try:
button = driver.find_element(By.ID, "submit")
button.click()
except NoSuchElementException:
time.sleep(5)
button = driver.find_element(By.ID, "submit")
button.click()
A condition-based wait is usually a better approach:
button = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable(
(By.ID, "submit")
)
)
button.click()
41. Retry Handling
Some failures may be temporary, particularly in highly dynamic applications. A retry mechanism can be useful when applied carefully.
from selenium.common.exceptions import StaleElementReferenceException
for attempt in range(3):
try:
button = driver.find_element(
By.ID, "submit"
)
button.click()
break
except StaleElementReferenceException:
print(
f"Attempt {attempt + 1} failed due to stale element"
)
Retries should not be used to hide genuine application defects or incorrect locators.
42. Retry with a Function
def click_with_retry(driver, locator, attempts=3):
for attempt in range(attempts):
try:
element = driver.find_element(*locator)
element.click()
return True
except StaleElementReferenceException:
if attempt == attempts - 1:
raise
return False
43. Exception Handling for Dynamic Elements
def safe_click(driver, locator):
try:
element = WebDriverWait(
driver, 10
).until(
EC.element_to_be_clickable(locator)
)
element.click()
return True
except TimeoutException:
print(
f"Element was not clickable: {locator}"
)
return False
except ElementClickInterceptedException:
print(
f"Click intercepted: {locator}"
)
return False
44. Safe Element Finding Utility
def find_element_safe(driver, locator):
try:
return driver.find_element(*locator)
except NoSuchElementException:
print(
f"Element not found: {locator}"
)
return None
45. Safe Text Retrieval
def get_text_safe(driver, locator):
try:
element = WebDriverWait(
driver, 10
).until(
EC.visibility_of_element_located(locator)
)
return element.text
except TimeoutException:
return None
except StaleElementReferenceException:
return None
46. Safe Page Navigation
def open_page(driver, url):
try:
driver.get(url)
return True
except WebDriverException as e:
print(
f"Unable to open page: {e}"
)
return False
47. Exception Handling with Frames
try:
WebDriverWait(driver, 10).until(
EC.frame_to_be_available_and_switch_to_it(
(By.ID, "payment-frame")
)
)
card = WebDriverWait(driver, 10).until(
EC.visibility_of_element_located(
(By.ID, "card-number")
)
)
card.send_keys("4111111111111111")
except TimeoutException:
print(
"Payment frame or card field was unavailable"
)
except NoSuchFrameException:
print("Payment frame was not found")
finally:
driver.switch_to.default_content()
48. Exception Handling with Windows
try:
original_window = driver.current_window_handle
driver.find_element(
By.ID, "open-window"
).click()
WebDriverWait(driver, 10).until(
EC.number_of_windows_to_be(2)
)
for handle in driver.window_handles:
if handle != original_window:
driver.switch_to.window(handle)
break
except TimeoutException:
print("New window did not open")
except NoSuchWindowException:
print("Window could not be accessed")
finally:
if original_window in driver.window_handles:
driver.switch_to.window(original_window)
49. Exception Handling with Alerts
try:
driver.find_element(
By.ID, "delete"
).click()
alert = WebDriverWait(
driver, 10
).until(
EC.alert_is_present()
)
print(alert.text)
alert.accept()
except TimeoutException:
print("Alert did not appear")
except NoAlertPresentException:
print("No alert was present")
50. Exception Handling with JavaScript
from selenium.common.exceptions import JavascriptException
try:
result = driver.execute_script(
"return document.title;"
)
print(result)
except JavascriptException as e:
print(
"JavaScript execution failed:",
e
)
51. Complete Selenium Exception Handling Framework Example
import logging
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import (
TimeoutException,
NoSuchElementException,
StaleElementReferenceException,
ElementClickInterceptedException,
WebDriverException
)
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s - %(levelname)s - %(message)s"
)
driver = None
try:
driver = webdriver.Chrome()
driver.get("https://example.com/login")
wait = WebDriverWait(driver, 10)
username = wait.until(
EC.visibility_of_element_located(
(By.ID, "username")
)
)
password = wait.until(
EC.visibility_of_element_located(
(By.ID, "password")
)
)
login_button = wait.until(
EC.element_to_be_clickable(
(By.ID, "login")
)
)
username.send_keys("admin")
password.send_keys("admin123")
login_button.click()
wait.until(
EC.url_contains("/dashboard")
)
logging.info("Login successful")
except TimeoutException as e:
logging.error(
"Timeout occurred: %s",
e
)
if driver:
driver.save_screenshot(
"timeout_failure.png"
)
except NoSuchElementException as e:
logging.error(
"Element not found: %s",
e
)
if driver:
driver.save_screenshot(
"element_failure.png"
)
except StaleElementReferenceException as e:
logging.error(
"Stale element: %s",
e
)
except ElementClickInterceptedException as e:
logging.error(
"Click intercepted: %s",
e
)
except WebDriverException as e:
logging.error(
"WebDriver exception: %s",
e
)
finally:
if driver:
driver.quit()
logging.info("Browser closed")
52. Exception Handling Flow in a Professional Framework
Test Starts
|
v
Open Browser
|
v
Execute Test Step
|
v
Exception?
/ \
No Yes
| |
v v
Continue Identify Type
|
+-----+-----+------+
| | | |
v v v v
Wait Locator Click Other
| | | |
+-----+-----+------+
|
v
Log Failure
|
v
Capture Evidence
|
v
Cleanup/Teardown
|
v
Test Report
53. Common Exception Handling Mistakes
Mistake 1: Catching Every Exception
try:
driver.find_element(By.ID, "login").click()
except:
pass
This hides the actual problem and makes debugging difficult.
Mistake 2: Empty Exception Handler
except Exception:
pass
An exception should normally be logged, handled, re-raised, or otherwise accounted for.
Mistake 3: Using sleep Instead of Proper Synchronization
except NoSuchElementException:
time.sleep(10)
Use an appropriate Selenium wait when the application condition is known.
Mistake 4: Catching WebDriverException Too Early
try:
...
except WebDriverException:
print("Error")
If this appears before more specific handlers, specific failures may not receive specialized handling.
Mistake 5: Not Re-Raising Test Failures
except AssertionError:
print("Test failed")
In many test frameworks, silently consuming an assertion failure can incorrectly prevent the test from being reported as failed. If the failure should remain a test failure, re-raise it after collecting diagnostics.
Mistake 6: Closing the Browser Too Early
Do not close the browser before collecting the evidence required for debugging.
54. Best Practices for Exception Handling in Selenium
- Catch specific Selenium exceptions whenever possible.
- Use explicit waits for dynamic application states.
- Do not use exceptions as the primary synchronization mechanism.
- Log meaningful error messages.
- Capture screenshots for important UI failures.
- Keep browser cleanup in a finally block or framework teardown mechanism.
- Re-raise failures when the test should remain failed.
- Use reusable utility functions for repeated error handling.
- Keep exception handling close to the operation when recovery is possible.
- Do not silently ignore exceptions.
- Use custom exceptions when they improve framework readability.
- Keep retry logic limited and purposeful.
- Record the locator, URL, test step, and exception type in framework logs.
- Use Page Object Model to organize page-specific interaction logic.
- Use test reports to expose failures clearly.
55. Exception Handling Strategy Table
| Exception | Typical Situation | Possible Response |
| NoSuchElementException | Element cannot be found | Check locator, page state, frame, and wait strategy |
| TimeoutException | Condition not satisfied in time | Check condition, locator, timeout, and application state |
| StaleElementReferenceException | Element reference is no longer valid | Locate the element again |
| ElementNotInteractableException | Element cannot currently be interacted with | Check visibility, enabled state, and UI state |
| ElementClickInterceptedException | Another element blocks the click | Wait for overlay or blocking element to disappear |
| InvalidElementStateException | Element is in an invalid state | Verify element state before operation |
| NoSuchFrameException | Frame cannot be found | Verify frame locator and context |
| NoSuchWindowException | Window/tab does not exist | Verify window handles |
| NoAlertPresentException | No alert is available | Wait for alert or verify application flow |
| UnexpectedAlertPresentException | Unexpected alert blocks command | Handle alert appropriately |
| InvalidSelectorException | Invalid XPath/CSS selector | Correct and validate locator |
| JavascriptException | JavaScript execution fails | Validate JavaScript |
| SessionNotCreatedException | Browser session cannot start | Check browser, driver, and configuration |
| NoSuchDriverException | Driver cannot be located | Check WebDriver setup |
| WebDriverException | General WebDriver failure | Log and investigate underlying cause |
56. Real-World Login Exception Handling
def login(driver, username, password):
wait = WebDriverWait(driver, 10)
try:
user_field = wait.until(
EC.visibility_of_element_located(
(By.ID, "username")
)
)
password_field = wait.until(
EC.visibility_of_element_located(
(By.ID, "password")
)
)
login_button = wait.until(
EC.element_to_be_clickable(
(By.ID, "login")
)
)
user_field.send_keys(username)
password_field.send_keys(password)
login_button.click()
wait.until(
EC.url_contains("/dashboard")
)
return True
except TimeoutException:
driver.save_screenshot(
"login_timeout.png"
)
return False
except WebDriverException as e:
driver.save_screenshot(
"login_webdriver_error.png"
)
print("WebDriver error:", e)
return False
57. Real-World E-Commerce Exception Handling
def add_product_to_cart(driver):
wait = WebDriverWait(driver, 15)
try:
product = wait.until(
EC.element_to_be_clickable(
(By.CSS_SELECTOR, ".product")
)
)
product.click()
add_button = wait.until(
EC.element_to_be_clickable(
(By.ID, "add-to-cart")
)
)
add_button.click()
wait.until(
EC.text_to_be_present_in_element(
(By.ID, "cart-message"),
"Added"
)
)
return True
except TimeoutException:
driver.save_screenshot(
"cart_timeout.png"
)
return False
except ElementClickInterceptedException:
driver.save_screenshot(
"cart_click_intercepted.png"
)
return False
except StaleElementReferenceException:
print(
"Product element became stale"
)
return False
58. Practical Project: Selenium Exception Handling Framework
Create a Selenium Python automation framework with centralized exception handling.
Requirements
- Create a BaseTest class.
- Create browser setup and teardown methods.
- Create reusable wait utilities.
- Create screenshot utilities.
- Create logging utilities.
- Create Page Object classes.
- Handle common Selenium exceptions.
- Capture screenshots on failures.
- Record exception details in logs.
- Re-raise failures when required.
- Generate a test report.
Suggested Project Structure
selenium_project/
|
+-- tests/
| +-- test_login.py
| +-- test_cart.py
|
+-- pages/
| +-- login_page.py
| +-- product_page.py
| +-- cart_page.py
|
+-- utilities/
| +-- wait_helper.py
| +-- screenshot_helper.py
| +-- logger.py
|
+-- exceptions/
| +-- custom_exceptions.py
|
+-- screenshots/
|
+-- logs/
|
+-- reports/
|
+-- conftest.py
59. Interview Questions on Exception Handling
Q1. What is exception handling?
Exception handling is a mechanism for detecting and managing runtime errors without allowing the program to terminate unexpectedly.
Q2. What is NoSuchElementException?
It occurs when Selenium cannot find the requested element at the time the lookup is performed.
Q3. What is TimeoutException?
It occurs when a Selenium wait condition is not satisfied within the configured timeout.
Q4. What is StaleElementReferenceException?
It occurs when a previously located element reference is no longer attached to the current DOM.
Q5. How do you handle stale elements?
Common approaches include waiting for the appropriate state and locating the element again after the DOM changes.
Q6. What is ElementClickInterceptedException?
It occurs when another element prevents Selenium from clicking the intended element.
Q7. What is the difference between try and except?
The try block contains potentially failing code, while the except block handles a matching exception.
Q8. What is finally?
The finally block executes whether an exception occurs or not and is useful for cleanup.
Q9. Why should specific exceptions be preferred?
Specific exceptions allow the framework to identify the actual failure type and apply an appropriate response.
Q10. Can we use multiple except blocks?
Yes. Multiple except blocks can handle different exception types separately.
Q11. What is raise?
The raise keyword manually creates or propagates an exception.
Q12. Can exception handling replace explicit waits?
No. Exception handling manages failures, while waits synchronize the automation with application state. They solve different problems.
Q13. What is WebDriverException?
WebDriverException is the base exception class for Selenium WebDriver-related exceptions.
Q14. How can screenshots help with exceptions?
A screenshot provides visual evidence of the browser state at the time of failure, which can help diagnose UI automation problems.
Q15. Why should exceptions not be silently ignored?
Silently ignoring exceptions can hide real application or automation defects and may produce misleading test results.
60. Quick Revision
| Python Concept | Purpose |
| try | Contains potentially failing code |
| except | Handles an exception |
| else | Runs when no exception occurs |
| finally | Runs regardless of exception |
| raise | Raises or propagates an exception |
| Exception | General Python exception base |
| WebDriverException | Selenium WebDriver exception base |
61. Selenium Exception Quick Revision
| Exception | Remember It As |
| NoSuchElementException | Element not found |
| TimeoutException | Condition timed out |
| StaleElementReferenceException | Element reference became invalid |
| ElementNotInteractableException | Element cannot be interacted with |
| ElementClickInterceptedException | Another element blocked click |
| InvalidElementStateException | Element is in an invalid state |
| NoSuchFrameException | Frame not found |
| NoSuchWindowException | Window/tab not found |
| NoAlertPresentException | No alert available |
| UnexpectedAlertPresentException | Unexpected alert appeared |
| InvalidSelectorException | Invalid locator expression |
| JavascriptException | JavaScript execution failed |
| SessionNotCreatedException | Browser session could not start |
| NoSuchDriverException | Driver could not be located |
| WebDriverException | General WebDriver error |
62. Recommended Exception Handling Flow
Perform Selenium Action
|
v
Was Action Successful?
/ \
Yes No
| |
v v
Continue Identify Exception
|
v
Specific Exception?
/ \
Yes No
| |
v v
Handle Specifically Log General Error
| |
+------ + -----+
|
v
Capture Screenshot
|
v
Collect Diagnostic Data
|
v
Retry / Recover / Fail
|
v
Cleanup
63. Final Summary
Exception Handling is an essential part of professional Selenium Python automation. Selenium interacts with browsers and dynamic web applications, so failures such as missing elements, timeouts, stale references, intercepted clicks, unavailable frames, missing windows, unexpected alerts, and invalid selectors can occur during test execution.
Python's try, except, else, finally, and raise mechanisms provide the foundation for handling these situations. Selenium adds specialized WebDriver exceptions that allow automation engineers to identify different failure conditions.
A reliable automation framework should combine proper waits, specific exception handling, logging, screenshots, cleanup, and appropriate failure propagation. Exception handling should make failures easier to diagnose rather than hide them.
64. Course Resources
Selenium Training: Selenium Training Course
Register for Course Demo: Register for Selenium Course Demo